package MyFitnessPlate.TestApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import MyFitnessPlate.DataSet.ParsedExerciseAddCategoryDataSet;
import MyFitnessPlate.DataSet.ParsedExerciseAddDescriptionDataSet;
import MyFitnessPlate.Handler.ExerciseAddCategoryHandler;
import MyFitnessPlate.Handler.ExerciseAddDescriptionHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class ExerciseAddActivity extends Activity {
    private ArrayList<Integer> exerciseDescriptionIdList = new ArrayList<Integer>();
	private ArrayList<Integer> exerciseCategoryIdList = new ArrayList<Integer>();
	private ArrayList<ParsedExerciseAddCategoryDataSet> exerciseCategoryList = new ArrayList<ParsedExerciseAddCategoryDataSet>();
	private ArrayList<ParsedExerciseAddDescriptionDataSet> exerciseDescriptionList = new ArrayList<ParsedExerciseAddDescriptionDataSet>();
	List<String> spinnerList = new ArrayList<String>();
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exercise_add_screen);
        
        final Button SubmitButton = (Button) findViewById(R.id.SubmitButton);
        final Spinner CategorySpinner = (Spinner) findViewById(R.id.CategorySpinner);
        final Spinner DescriptionSpinner = (Spinner) findViewById(R.id.DescriptionSpinner);
        final Spinner TimeSpinner = (Spinner) findViewById(R.id.TimeSpinner);
      
		//Populate category spinner
		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		categoryAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
		CategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        	public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        		DescriptionSpinner.setAdapter(loadDescriptions(i)); }
        	public void onNothingSelected(AdapterView<?> adapterView) { return; }
        });

		//Load categories.
		loadCategories();
		for (ParsedExerciseAddCategoryDataSet peacds : exerciseCategoryList){
    		if(peacds != null ){
    			categoryAdapter.add(peacds.getCategoryName());
    			exerciseCategoryIdList.add(peacds.getId());
    		}
    	}	
		
		//Load category, description, and time spinners.
		CategorySpinner.setAdapter(categoryAdapter);
		DescriptionSpinner.setAdapter(loadDescriptions(CategorySpinner.getSelectedItemPosition()));		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.exercise_time, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		TimeSpinner.setAdapter(adapter);
		
		SubmitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	insertExercise(CategorySpinner.getSelectedItemPosition(), DescriptionSpinner.getSelectedItemPosition(), TimeSpinner.getSelectedItem().toString().trim());	
            }
        });	
    }
	
	private void insertExercise(Integer category,Integer description, String time) {
		String User = getIntent().getExtras().getString("User");
		URL url;
		try {
			url = new URL("http://myfitnessplate.com/api/new-exercise-log/username/"+User+"/id/"+exerciseDescriptionList.get(description).getId()+"/category/"+exerciseCategoryList.get(category).getId()+"/duration/"+time+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
			in.close();
			//Notify them of the 
			final AlertDialog alertDialog = new AlertDialog.Builder(ExerciseAddActivity.this).create();
	    	alertDialog.setTitle("Added");
	    	alertDialog.setMessage("The item has been added to the list.");
	    	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	    		public void onClick(DialogInterface dialog, int which) {
	    			alertDialog.dismiss();
	    			ExerciseAddActivity.this.finish();
	    		}
	    	});
	    	alertDialog.show();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ArrayAdapter<String> loadDescriptions(Integer position){
		try {
			URL Url = new URL("http://myfitnessplate.com/api/fetch-exercise-category/id/"+exerciseCategoryList.get(position).getId()+ "/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			ExerciseAddDescriptionHandler myExerciseAddDescriptionHandler = new ExerciseAddDescriptionHandler();
			xr.setContentHandler(myExerciseAddDescriptionHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(Url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			exerciseDescriptionList = myExerciseAddDescriptionHandler.getParsedData();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}  catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
		
		//Populate category spinner
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
			exerciseDescriptionIdList.clear();
			for (ParsedExerciseAddDescriptionDataSet peadds : exerciseDescriptionList){
    		if(peadds != null){
    			adapter.add(peadds.getDescriptionName());
    			exerciseDescriptionIdList.add(peadds.getId());
    		}
    	}
		
		return adapter;
	}
	
	public void loadCategories(){
		try {
			URL Url = new URL("http://myfitnessplate.com/api/fetch-exercise-categories/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			ExerciseAddCategoryHandler myExerciseAddCategoryHandler = new ExerciseAddCategoryHandler();
			xr.setContentHandler(myExerciseAddCategoryHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(Url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			
			exerciseCategoryList = myExerciseAddCategoryHandler.getParsedData();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}  catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
	}

    private void handleError(String tag, String message, Exception e) {
		Log.d(tag, message);
		e.printStackTrace();
	}
}